package com.neusoft.controller;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/GPTController")
public class GPTController {

    private static final String GPT_API_URL = "https://api.chatanywhere.tech/v1/chat/completions";

    @GetMapping("/query/{content}")
    public String queryGPT(@PathVariable("content") String content) {
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(GPT_API_URL);
            request.addHeader("Content-Type", "application/json");
            request.addHeader("Authorization", "Bearer sk-4Qk7N2YHopThrH5ueJW6AFVVcTpZYryuJ998RIRzGOsoA7bh");

            JsonObject requestJson = new JsonObject();
            requestJson.addProperty("model", "gpt-3.5-turbo");

            // 创建 messages 数组
            JsonArray messagesArray = new JsonArray();
            JsonObject message = new JsonObject();
            message.addProperty("role", "user");
            message.addProperty("content", content);
            messagesArray.add(message);
            requestJson.add("messages", messagesArray);

            HttpEntity entity = new StringEntity(requestJson.toString(), ContentType.APPLICATION_JSON);
            request.setEntity(entity);

            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String jsonResponse = EntityUtils.toString(responseEntity);
                    if (statusCode == 200) {
                        // 解析JSON响应以获取 content
                        JsonObject responseJson = JsonParser.parseString(jsonResponse).getAsJsonObject();
                        JsonArray choices = responseJson.getAsJsonArray("choices");
                        if (choices != null && choices.size() > 0) {
                            JsonObject firstChoice = choices.get(0).getAsJsonObject();
                            JsonObject messageObj = firstChoice.getAsJsonObject("message");
                            if (messageObj != null) {
                                String resultContent = messageObj.get("content").getAsString();
                                return resultContent; // 返回消息内容
                            }
                        }
                        return "No content available";
                    } else {
                        return "Error: Received HTTP " + statusCode + " - " + jsonResponse;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
        return "No response from GPT service";
    }
}
